import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Tree, message } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { getPlanPermissions, assignPermissions } from './permission-api';
import * as permissionApi from '@/api/permission';
import type { Permission } from '@/types';

interface PermissionModalProps {
  visible: boolean;
  planId: string;
  planName: string;
  onClose: () => void;
}

const PermissionModal: React.FC<PermissionModalProps> = ({
  visible,
  planId,
  planName,
  onClose,
}) => {
  const [loading, setLoading] = useState(false);
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

  // 加载所有权限（只在组件挂载时加载一次）
  useEffect(() => {
    fetchPermissions();
  }, []);

  // 加载套餐已分配的权限
  useEffect(() => {
    if (visible && planId) {
      loadPlanPermissions();
    }
  }, [visible, planId]);

  const fetchPermissions = async () => {
    try {
      const response = await permissionApi.getPermissions({ pageSize: 10000 });
      if (response.data.success) {
        setPermissions(response.data.data);
      }
    } catch (error) {
      console.error('Failed to fetch permissions:', error);
    }
  };

  const loadPlanPermissions = async () => {
    setLoading(true);
    try {
      const response = await getPlanPermissions(planId);
      if (response.data.success) {
        setSelectedPermissions(response.data.data);
      }
    } catch (error) {
      console.error('Failed to load plan permissions:', error);
      message.error('加载权限失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    setLoading(true);
    try {
      await assignPermissions({
        planId,
        permissionIds: selectedPermissions,
      });
      message.success('权限分配成功');
      onClose();
    } catch (error) {
      console.error('Failed to assign permissions:', error);
      message.error('权限分配失败');
    } finally {
      setLoading(false);
    }
  };

  // 转换权限为树形数据（按模块分组，二级结构）
  const permissionTreeData: DataNode[] = useMemo(() => {
    const moduleMap = new Map<string, Permission[]>();

    // 按 module 分组，过滤掉系统权限
    permissions.forEach(permission => {
      if (permission.isSystem) return;

      const module = permission.module || 'other';
      if (!moduleMap.has(module)) {
        moduleMap.set(module, []);
      }
      moduleMap.get(module)!.push(permission);
    });

    // 转换为树形结构：模块 -> 权限列表
    return Array.from(moduleMap.entries())
      .sort((a, b) => {
        // 按第一个权限的 sortOrder 排序
        const sortA = a[1][0]?.sortOrder || 999;
        const sortB = b[1][0]?.sortOrder || 999;
        return sortA - sortB;
      })
      .map(([module, perms]) => {
        const moduleName = perms[0]?.moduleName || module;

        return {
          title: moduleName,
          key: module,
          children: perms
            .sort((a, b) => (a.sortOrder || 999) - (b.sortOrder || 999))
            .map(p => ({
              title: p.description || `${p.resource}:${p.action}`,
              key: p.id,
            })),
        };
      });
  }, [permissions]);

  return (
    <Modal
      title={`配置套餐权限 - ${planName}`}
      open={visible}
      onOk={handleSave}
      onCancel={onClose}
      confirmLoading={loading}
      width={600}
      bodyStyle={{
        maxHeight: '60vh',
        overflowY: 'auto',
        padding: '24px',
      }}
      destroyOnClose
    >
      <div style={{ marginBottom: 16, padding: '8px 12px', background: '#e6f7ff', border: '1px solid #91d5ff', borderRadius: '4px' }}>
        <div style={{ fontSize: '14px', color: '#0958d9' }}>
          <strong>提示：</strong>为套餐配置权限后，订阅该套餐的租户将自动获得这些权限。系统权限（如租户管理、套餐管理）不可分配。
        </div>
      </div>

      <Tree
        checkable
        defaultExpandAll
        treeData={permissionTreeData}
        checkedKeys={selectedPermissions}
        onCheck={(checkedKeys) => {
          setSelectedPermissions(checkedKeys as string[]);
        }}
      />
    </Modal>
  );
};

export default PermissionModal;
